package com.jams.goodox.activity.serve.park;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.hangzhou.jin.customview.LoadView;
import com.hangzhou.jin.customview.SpaceItemDecoration;
import com.jams.goodox.BaseFragment;
import com.jams.goodox.R;
import com.jams.goodox.activity.ChoosePayActivity;
import com.jams.goodox.constant.Constant;
import com.jams.goodox.constant.Constants;
import com.jams.goodox.entity.PageInfo;
import com.jams.goodox.entity.ParkHistoryBean;
import com.jams.goodox.entity.PayInfo;
import com.jams.goodox.entity.resp.ParkHistoryResp;
import com.jams.goodox.net.RetrofitCallbackListener;
import com.jams.goodox.net.services.ServiceService;
import com.jams.goodox.utils.DataCacheManager;
import com.jams.goodox.utils.DensityUtil;
import com.jams.goodox.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
/**
 * 停车申请记录页签
 * Created by jams_zhen on 2017/5/24.
 */

public class ParkHistoryFragment extends BaseFragment{

    @Bind(R.id.recycleView)
    RecyclerView recycleView;
    @Bind(R.id.loadView)
    LoadView loadView;
    @Bind(R.id.swipeRefresh)
    SwipeRefreshLayout swipeRefresh;

    private BaseQuickAdapter baseQuickAdapter;

    private List<ParkHistoryBean> parkHistoryBeanList;

    private boolean isCanUse;//是否有效订单

    private int curPage = 1;
    private boolean isPersonPark;

    public static ParkHistoryFragment getInstance(boolean canUse,boolean isPersonPark){
        ParkHistoryFragment parkHistoryFragment=new ParkHistoryFragment();
        Bundle bundle=new Bundle();
        bundle.putBoolean("canUse",canUse);
        bundle.putBoolean("isPersonPark",isPersonPark);
        parkHistoryFragment.setArguments(bundle);
        return parkHistoryFragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.meet_history_fragment, container, false);
        ButterKnife.bind(this, view);

        isCanUse=getArguments().getBoolean("canUse");
        isPersonPark=getArguments().getBoolean("isPersonPark");

        parkHistoryBeanList=new ArrayList<>();
        recycleView.setLayoutManager(new LinearLayoutManager(mContext));
        baseQuickAdapter = new BaseQuickAdapter<ParkHistoryBean>(R.layout.park_history_item,parkHistoryBeanList) {
            @Override
            protected void convert(BaseViewHolder baseViewHolder,final ParkHistoryBean parkHistoryBean) {
                baseViewHolder.setText(R.id.tx_car_num,parkHistoryBean.getCarNum());
                baseViewHolder.setText(R.id.tx_unit_price_num,parkHistoryBean.getUnitPriceNum());

                TextView txEnTime=baseViewHolder.getView(R.id.tx_en_time);//设置状态
                String enTime=parkHistoryBean.getEnTime();
                txEnTime.setText(enTime);
                switch (parkHistoryBean.getParkType()){
                    case ParkHistoryBean.Type_Park_Need_pay:
                        txEnTime.setVisibility(View.GONE);
                        break;
                    case ParkHistoryBean.Type_Park_Commend:
                        txEnTime.setVisibility(View.VISIBLE);
                        if(enTime.contains("到期")){//可续约，显示到期时间
                            txEnTime.setTextColor(ContextCompat.getColor(getContext(),R.color.orange));
                        }else {
                            txEnTime.setTextColor(ContextCompat.getColor(getContext(),R.color.blue));
                        }
                        break;
                    case ParkHistoryBean.Type_Park_Past_Close:
                        txEnTime.setVisibility(View.VISIBLE);
                        txEnTime.setTextColor(ContextCompat.getColor(getContext(),R.color.font_color_gray));
                        break;
                    default:
                        txEnTime.setVisibility(View.GONE);
                        break;
                }
                boolean needPay=ParkHistoryBean.Type_Park_Need_pay.equalsIgnoreCase(parkHistoryBean.getParkType());//标识是否是支付
                baseViewHolder.setVisible(R.id.tx_empty_time,needPay);
                baseViewHolder.setText(R.id.tx_empty_time, enTime);

                baseViewHolder.setText(R.id.tx_continue_time,parkHistoryBean.getContinueTime());
                baseViewHolder.setText(R.id.tx_order_num,parkHistoryBean.getOrderNo());

                baseViewHolder.setText(R.id.tx_pay,ParkHistoryBean.Type_Park_Need_pay.equalsIgnoreCase(parkHistoryBean.getParkType())?"付款":"续约");

                baseViewHolder.setVisible(R.id.relative_pay,parkHistoryBean.isShowBottomView());//仅待付款or可续约显示底部按钮

                baseViewHolder.setOnClickListener(R.id.tx_pay, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        switch (parkHistoryBean.getParkType()){
                            case ParkHistoryBean.Type_Park_Need_pay:
                                goPay(parkHistoryBean);
                                break;
                            case ParkHistoryBean.Type_Park_Commend:
                                Intent in=new Intent(getContext(),ParkingApplyActivity.class);
                                in.putExtra("orderId",parkHistoryBean.getOrderId());
                                startActivity(in);
                                break;
                        }
                    }
                });
            }
        };
        recycleView.setAdapter(baseQuickAdapter);
        baseQuickAdapter.openLoadMore(PAGE_SIZE, true);

        // 自定义上拉View
        baseQuickAdapter.setLoadingView(getLoadMoreBootView(mContext));

        baseQuickAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                loadData(true);
            }
        });
        recycleView.addItemDecoration(new SpaceItemDecoration(DensityUtil.dp2px(getContext(), 8)));
        loadView.loading();
        loadData(false);
        swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshData();
            }
        });
        baseQuickAdapter.setOnRecyclerViewItemClickListener(new BaseQuickAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int i) {
                Intent intent = new Intent(getContext(),ParkOrderDetailActivity.class);
                intent.putExtra("OrderId",parkHistoryBeanList.get(i).getOrderId());
                intent.putExtra("payInfo",parkHistoryBeanList.get(i).getPay());
                intent.putExtra("isPersonPark",isPersonPark);
                startActivityForResult(intent,Constants.REQUEST_SIMPLE);
            }
        });
        return view;
    }

    /**
     * 付款
     */
    private void goPay(ParkHistoryBean parkHistoryBean){
        PayInfo payInfo=parkHistoryBean.getPay();//支付对象
        if(payInfo==null)return;
        Intent intent = new Intent(mContext, ChoosePayActivity.class);
        if (parkHistoryBean.getRedPicketMoney()!=0)payInfo.setRedPacketMoney(parkHistoryBean.getRedPicketMoney());
//        intent.putExtra("come", 1);//直接返回
        if(isPersonPark) {//个人下单传递 1 企业下单 2
            payInfo.setOrderCreateClassfiy(1);
        }else {
            payInfo.setOrderCreateClassfiy(2);
        }
        payInfo.setPaySubCode(Constants.PARKING_CODE);//该字段用于余额支付，支付成功返回
        payInfo.setServerName("停车申请");
        payInfo.setOrderAllMoney(parkHistoryBean.getOrderAllPay());
        payInfo.setThirdPayConfigType(Constants.PayType.Type_Parking);
        intent.putExtra("payInfo", payInfo);
        startActivity(intent);
    }

    private void loadData(boolean isLoadMore) {
        Map<String,String> params= Constant.getPagerParams(isLoadMore?curPage+1:curPage);
        if(!isPersonPark) params.put("enterpriseId", DataCacheManager.getInstance().getUser().getEnterpriseId());
        params.put("recordStatus",isCanUse?"1":"0");
        enqueue(createCallService(ServiceService.class).getParkList(params),new RetrofitCallbackListener<ParkHistoryResp>() {
            @Override
            public void onSuccess(Call<ParkHistoryResp> call, ParkHistoryResp result) {
                loadView.loadComplete();
                swipeRefresh.setRefreshing(false);
                if(result.getData()==null||result.getData().getResultList()==null||result.getData().getPageInfo()==null){
                    if(parkHistoryBeanList.size()==0)loadView.loadCompleteNoData(R.mipmap.holder_no_history,"暂无记录");
                    baseQuickAdapter.notifyDataChangedAfterLoadMore(false);
                    return;
                }
                PageInfo pageInfo = result.getData().getPageInfo();
                curPage = pageInfo.getCurPage();
                if(curPage==1)parkHistoryBeanList.clear();
                parkHistoryBeanList.addAll(result.getData().transform());
                baseQuickAdapter.notifyDataChangedAfterLoadMore(pageInfo.isHasMore());
                if(parkHistoryBeanList.size()==0)loadView.loadCompleteNoData(R.mipmap.holder_no_history,"暂无记录");
            }

            @Override
            public void onError(String msg) {
                loadView.loadComplete();
                swipeRefresh.setRefreshing(false);
                baseQuickAdapter.notifyDataChangedAfterLoadMore(false);
                if(parkHistoryBeanList.size()==0)loadView.loadCompleteNoData(R.mipmap.holder_no_history,"暂无记录");
                ToastUtil.show(msg);
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==Constants.REQUEST_SIMPLE&&resultCode==Constants.RESULT_OK_SIMPLE){
            swipeRefresh.setRefreshing(true);
            refreshData();
        }
    }

    /**
     * 刷新调用
     */
    private void refreshData(){
        // 刷新代码
        curPage=1;
        loadData(false);
    }
}
